package com.jdy.haoduoai.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.Uri;
import android.provider.MediaStore;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class ImageUtils {

  public static String getImagePath(String remoteUrl) {
    String imageName = remoteUrl.substring(remoteUrl.lastIndexOf("/") + 1,
        remoteUrl.length());
    String path = PathUtil.getInstance().getImagePath() + "/" + imageName;
    LeXiaoXiaoBanLog.d("msg", "image path:" + path);
    return path;

  }

  public static String getThumbnailImagePath(String thumbRemoteUrl) {
    String thumbImageName = thumbRemoteUrl.substring(
        thumbRemoteUrl.lastIndexOf("/") + 1, thumbRemoteUrl.length());
    String path = PathUtil.getInstance().getImagePath() + "/" + "th"
        + thumbImageName;
    LeXiaoXiaoBanLog.d("msg", "thum image path:" + path);
    return path;
  }

  public static Bitmap getBitmapFromUri(Context context, Uri uri) {
    try {
      return MediaStore.Images.Media.getBitmap(context.getContentResolver(),
          uri);
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return null;
  }

  public static InputStream getBitmapInputStream(Bitmap targetBitmap) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    targetBitmap.compress(CompressFormat.PNG, 0 /* ignored for PNG */, bos);
    byte[] bitmapdata = bos.toByteArray();
    ByteArrayInputStream bs = new ByteArrayInputStream(bitmapdata);
    return bs;
  }

  public static InputStream getBitmapInputStream(Context context, Uri imageUri) {
    try {
      return context.getContentResolver().openInputStream(imageUri);
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return null;
  }

  /**
   * Downsample the image to avoid outofmemory exception.
   * 
   * @param selectedImage
   * @return
   * @throws FileNotFoundException
   */
  public static Bitmap decodeBitmapInputStream(InputStream bitmapInputStream,
      int requiredWidth, int requiredHeight) throws FileNotFoundException {
    // Decode image size
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(bitmapInputStream, null, o);

    // Find the correct scale value. It should be the power of 2.
    int width_tmp = o.outWidth, height_tmp = o.outHeight;
    int scale = 1;
    while (true) {
      if (width_tmp / 2 < requiredWidth || height_tmp / 2 < requiredHeight) {
        break;
      }
      width_tmp /= 2;
      height_tmp /= 2;
      scale *= 2;
    }

    // Decode with inSampleSize
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;
    return BitmapFactory.decodeStream(bitmapInputStream, null, o2);
  }

  public static Bitmap decodeScaleImage(String thumbnailPath, int i, int j) {
    
    return null;
  }

  public static int readPictureDegree(String path) {
    
    return 0;
  }

  /**
   * crop the bitmap to circle
   * 
   * @param bitmap
   * @return
   */
  public static Bitmap getCroppedBitmap(Bitmap bitmap) {
    Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(),
        Config.ARGB_8888);
    Canvas canvas = new Canvas(output);

    final int color = 0xff424242;
    final Paint paint = new Paint();
    final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());

    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(color);
    // canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
    canvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2,
        bitmap.getWidth() / 2, paint);
    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
    canvas.drawBitmap(bitmap, rect, rect, paint);
    // Bitmap _bmp = Bitmap.createScaledBitmap(output, 60, 60, false);
    // return _bmp;
    return output;
  }

  /**
   * Scale target image.
   * 
   * @param original
   * @param targetWidth
   * @param targetHeight
   * @return
   */
  public static Bitmap scaleCropToFit(Bitmap original, int targetWidth,
      int targetHeight, boolean circle) {
    // Need to scale the image, keeping the aspect ration first
    int width = original.getWidth();
    int height = original.getHeight();

    float widthScale = (float) targetWidth / (float) width;
    float heightScale = (float) targetHeight / (float) height;
    float scaledWidth;
    float scaledHeight;

    int startY = 0;
    int startX = 0;

    if (widthScale > heightScale) {
      scaledWidth = targetWidth;
      scaledHeight = height * widthScale;
      // crop height by...
      startY = (int) ((scaledHeight - targetHeight) / 2);
    } else {
      scaledHeight = targetHeight;
      scaledWidth = width * heightScale;
      // crop width by..
      startX = (int) ((scaledWidth - targetWidth) / 2);
    }

    Bitmap scaledBitmap = Bitmap.createScaledBitmap(original,
        (int) scaledWidth, (int) scaledHeight, true);

    Bitmap resizedBitmap = Bitmap.createBitmap(scaledBitmap, startX, startY,
        targetWidth, targetHeight);

    if (circle) {
      return getCroppedBitmap(resizedBitmap);
    } else {
      return resizedBitmap;
    }
  }

  /**
   * Add amount of color to the border of the bitmap.
   * 
   * @param bmp
   * @param borderColor
   * @param borderSize
   * @return
   */
  public static Bitmap addBorder(Bitmap bmp, int borderColor, int borderSize) {
    Bitmap bmpWithBorder = Bitmap.createBitmap(bmp.getWidth() + borderSize * 2,
        bmp.getHeight() + borderSize * 2, bmp.getConfig());
    Canvas canvas = new Canvas(bmpWithBorder);
    canvas.drawColor(borderColor);
    canvas.drawBitmap(bmp, borderSize, borderSize, null);
    return bmpWithBorder;
  }

  /**
   * Crop four round corners for the image.
   * 
   * @param bitmap
   * @return
   */
  public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundSize) {
    Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(),
        Config.ARGB_8888);
    Canvas canvas = new Canvas(output);

    final int color = 0xff424242;
    final Paint paint = new Paint();
    final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
    final RectF rectF = new RectF(rect);
    final float roundPx = roundSize;

    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(color);
    canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
    canvas.drawBitmap(bitmap, rect, rect, paint);

    return output;
  }

  public static Bitmap convertLayoutToBitmap(ViewGroup view) {
    view.setDrawingCacheEnabled(true);
    // this is the important code :)
    // Without it the view will have a dimension of 0,0 and the bitmap will be
    // null

    view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
        MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));

    view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());

    view.buildDrawingCache(true);
    Bitmap b = Bitmap.createBitmap(view.getDrawingCache());
    view.setDrawingCacheEnabled(false); // clear drawing cache
    return b;
  }
}
